<?php
/* 资金管理控制器 */
define('NUM_PER_PAGE', 20); // 每页显示数量
 
class My_moneyApp extends MemberbaseApp
{
    /* 构造函数 */
    function __construct()
    {
         $this->My_moneyApp();
    }

    function My_moneyApp()
    {
        parent::__construct();
		$this->my_money_mod =& m('my_money');
		$this->my_moneylog_mod =& m('my_moneylog');

    }
 	function index()//默认显示
    {
		$user_id = $this->visitor->get('user_id');
		$page = $this->_get_page(30);	
        $con = array(
            array(      //按收支类型搜索
                'field' => 'leixing',
                'name'  => 'type',
            ),		
            array(      //按下单时间搜索,起始时间
                'field' => 'add_time',
                'name'  => 'add_time_from',
                'equal' => '>=',
                'handler'=> 'gmstr2time',
            ),
            array(      //按下单时间搜索,结束时间
                'field' => 'add_time',
                'name'  => 'add_time_to',
                'equal' => '<=',
                'handler'=> 'gmstr2time_end',
            ),
        );
        $conditions = $this->_get_query_conditions($con);
		$my_money=$this->my_moneylog_mod->find(array(
            'conditions' => "user_id='$user_id' and user_log_del=0 and caozuo=1" . $conditions,
			'order' => 'add_time desc',
            'limit' => $page['limit'],
			'count' => true,
        ));	
		foreach ($my_money as $key => $mymoney)
		{
			if ($mymoney['s_and_z'] == 1){
				$my_money[$key]['money_sr'] = $mymoney['money'];//收入
			}elseif ($mymoney['s_and_z'] == 2){
				$my_money[$key]['money_zc'] = $mymoney['money'];//支付
			}
		}
		$page['item_count'] = $this->my_moneylog_mod->getCount();
        $this->_format_page($page);
	    $this->assign('page_info', $page);
		$this->assign('my_money', $my_money);	
		$this->assign('money_money', $money_money);
		$this->_curitem('my_money_index');
		$this->_curmenu('my_money_index');
		
		//收入、支出总计
		if($my_money)
		{
			$sql_sr= "SELECT sum(money) as money_total FROM {$this->my_moneylog_mod->table} WHERE user_id='$user_id' and user_log_del=0 and caozuo=1 and s_and_z=1 ". $conditions;
			$sql_zc= "SELECT sum(money) as money_total FROM {$this->my_moneylog_mod->table} WHERE user_id='$user_id' and user_log_del=0 and caozuo=1 and s_and_z=2 ". $conditions;
			$money_total['money_sr_total'] = $this->my_moneylog_mod->getOne($sql_sr);
			$money_total['money_zc_total'] = $this->my_moneylog_mod->getOne($sql_zc);
			$this->assign('money_total', $money_total);	
		}

		$this->_config_seo('title', Lang::get('member_center') . ' - ' . Lang::get('my_money_index'));
	    $this->import_resource(array('script' => 'inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
									'style'=> 'jquery.ui/themes/ui-lightness/jquery.ui.css'));	   
		$money_money=$this->my_money_mod->getRow("select money,money_dj,rz_is_ok from ".DB_PREFIX."my_money where user_id='$user_id'");	
		$this->assign('money_money', $money_money);	
		$this->display('my_money.index.html');
    }
	function remit_alipay()//网上充值
	{
		if ($_POST)
		{
			$money = empty($_POST['money']) ? 0 : round($_POST['money']);
			$ebank_type = $_POST['ebank_type'];
			if ( $money <= 0)
			{
                $this->show_warning('couwu_pay_money_err'); 
                return;
			}
			if (empty($ebank_type))
			{
                $this->show_warning('couwu_pay_bank_err'); 
                return;
			}			

			//添加日志
			$log_text =$this->visitor->get('user_name').'账户现金充值'.$money.Lang::get('yuan');
			$add_mymoneylog=array(
				'user_id'=>$this->visitor->get('user_id'),
				'user_name'=>$this->visitor->get('user_name'),
				'bank_name'=>$ebank_type,
				'add_time'=>gmtime(),
				'leixing'=>30, //帐号充值	
				//'money_zs'=>$money,
				'money'=>$money,
				'log_text'=>$log_text,		
				's_and_z'=>1,//收入1,支出2	
				'pay_order_sn'=> $this->_gen_order_sn(),//生成支付订单
			);
			$id = $this->my_moneylog_mod->add($add_mymoneylog);
			if ($this->my_moneylog_mod->has_error())
			{
				$this->show_warning($this->my_moneylog_mod->get_error());
				return;
			}			
			header('Location:index.php?app=my_money&act=remit_ailpay_confirm&id=' . $id);
		}else{
			$user_id = $this->visitor->get('user_id');
			$money_money=$this->my_money_mod->getOne("select money from ".DB_PREFIX."my_money where user_id='$user_id'");		
			$this->assign('money_money', $money_money);
			$this->_curitem('remit_alipay');
			$this->_curmenu('remit_alipay');
			$this->_config_seo('title', Lang::get('member_center') . ' - ' . Lang::get('remit_alipay'));
			$this->display('my_money.remit_alipay.html');
		}
	}
	function remit_bank()//银行充值
	{
		$user_id = $this->visitor->get('user_id');
		$money_money=$this->my_money_mod->getOne("select money from ".DB_PREFIX."my_money where user_id='$user_id'");		
		$this->assign('money_money', $money_money);		
		$this->_curitem('remit_bank');
        $this->_curmenu('remit_bank');
        $this->_config_seo('title', Lang::get('member_center') . ' - ' . Lang::get('remit_bank'));
		$this->display('my_money.remit_bank.html');
	}	
	function audit_ailpay()//网上银行充值记录
	{
	    $user_id = $this->visitor->get('user_id');
		$month = empty($_GET['month']) ? 0 : intval($_GET['month']);
		if ($month == 1){
			$times = strtotime('-1 months');
			$conditions = " and add_time > '$times'";
		}elseif($month == 2){
			$times = strtotime('-3 months');
			$conditions = " and add_time > '$times'";
		}elseif($month == 3){
			$times = strtotime('-6 months');
			
			$conditions = " and add_time > '$times'";
		}elseif($month == 4){
			$times = strtotime('-6 months');
			$conditions = " and add_time < '$times'";
		}else{
			$conditions = " and 1=1";
		}
		$page = $this->_get_page(NUM_PER_PAGE);		
		$my_money=$this->my_moneylog_mod->find(array(
            'conditions' => "user_id='$user_id' and user_log_del=0 and (leixing=30 or leixing=20) " . $conditions,
			'order' => 'add_time desc',
            'limit' => $page['limit'],
			'count' => true,
        ));	
		$ebank_type_check = Lang::get('ebank_type');//银行信息
		foreach ($my_money as $key => $mymoney)
		{
			if ($ebank_type_check[$mymoney['bank_name']])
			{
				$my_money[$key]['bank_name_check'] = $ebank_type_check[$mymoney['bank_name']];
			}else{
				$my_money[$key]['bank_name_check'] = $mymoney['bank_name'];
			}			
		}
		$page['item_count'] = $this->my_moneylog_mod->getCount();
        $this->_format_page($page);
	    $this->assign('page_info', $page);
		$this->assign('my_money', $my_money);	
		$this->assign('money_money', $money_money);
		$this->_curitem('audit_ailpay');
		$this->_curmenu('audit_ailpay');
		$this->_config_seo('title', Lang::get('member_center') . ' - ' . Lang::get('audit_ailpay'));
		$this->display('my_money.audit_ailpay.html');
	}
	function remit_ailpay_confirm()//网上银行确认充值信息
	{
		$this->show_warning("网站充值功能暂时关闭，敬请谅解");
		return;
		$id = intval($_GET['id']);
		if (!$id)
		{
			$this->show_warning('feifacanshu'); 
			return;
		}
		$my_money=$this->my_moneylog_mod->get(array('conditions' => "id='$id'"));	
		if ($my_money['caozuo'])
		{
			$this->show_warning('gaidingdanyijingzhifule'); 
			return;
		}
		$ebank_type_check = Lang::get('ebank_type');//银行信息
		if ($ebank_type_check[$my_money['bank_name']])
		{
			$my_money['bank_name_check'] = $ebank_type_check[$my_money['bank_name']];
		}else{
			$my_money['bank_name_check'] = $my_money['bank_name'];
		}
		$this->assign('my_money', $my_money);
		$this->_curitem('remit_alipay');
		$this->_curmenu('remit_ailpay_confirm');
		$this->_config_seo('title', Lang::get('member_center') . ' - ' . Lang::get('remit_ailpay_confirm'));		
		$this->display('my_money.remit_ailpay_confirm.html');
	}
	//账户提现
	function encash_bank()
	{
		$user_id = $this->visitor->get('user_id');
		$money_money=$this->my_money_mod->getRow("select * from ".DB_PREFIX."my_money where user_id='$user_id'");
		if($_POST)
		{
//			if (!$this->visitor->get('store_id'))
//			{
//				$this->show_warning('很抱歉，买家无法提现');
//				return;					
//			}
			if ($money_money['rz_is_ok'] < 3)
			{
				  $this->show_warning('您还没有通过实名认证，无法申请提款');
				  return;				
			}			
			$amount = htmldecode($_POST['amount']);
			$password = htmldecode($_POST['password']);
			if (!is_numeric($amount))
			{
				$this->show_warning('请输入正确的金额，必须为数字');
				return;				
			}
			if ( $amount < Conf::get('user_tikuan') )
			{
				$this->show_warning('最低结款金额为'.Conf::get('user_tikuan').''.Lang::get('money_danwei').'，请重新输入');
				return;					
			}	
			if(empty($password))
			{
				$this->show_warning('请输入您的支付密码'); 
				return;
			}					
			if (intval($money_money['money']) <= 0)
			{
				$this->show_warning('您的帐户余额小于或等于0'.Lang::get('money_danwei').'，无法结款');
				return;				
			}
			if ( $amount > $money_money['money'] )
			{
				$this->show_warning('输入的金额已经超过了您的余额，请重新输入');
				return;					
			}	
			$md5y_pass=md5($password);//转换32位 MD5
			if($money_money['zf_pass'] != $md5y_pass)
			{
				$this->show_warning('支付密码错误，请重新输入'); 
				return;	
			}		
			//自动生成订单编号
			$dingdanhao = date("Y-m-dH-i-s");
			$dingdanhao = str_replace("-","",$dingdanhao);
			$dingdanhao .= rand(1000,99999);

			//所有的判断都通过了，好，开始结款操作			
			$add_data = array(
			        'order_sn'       => $dingdanhao,
					'user_id'       => $user_id,
					'money'         => $amount,
					'real_name'     => htmldecode($_POST['real_name']),
					'bank_name'     => htmldecode($_POST['bank_name']),
					'bank_account'  => htmldecode($_POST['bank_account']),
					'leixing'       => 1,
					'add_time'      => gmtime(),
			);
			$my_moneytx_mod = & m('my_moneytx');
			$my_moneytx_mod->add($add_data);		
			//更新会员的金额
			$update_money = array(
			      'money'=> $money_money['money']-$amount,
				  'money_dj'=> $money_money['money_dj']+$amount,
			);
			$this->my_money_mod->edit('user_id='.$user_id,$update_money);				
            $this->show_message('提现申请提交成功，请等待审核',
            'back_list', 'index.php?app=my_money&act=tx_log'
			);
			
		}else{
			
			$this->assign('money_money', $money_money);	
			$this->assign('user_tikuan',Conf::get('user_tikuan'));
			$this->_curitem('encash_bank');
			$this->_curmenu('encash_bank');
			$this->_config_seo('title', Lang::get('member_center') . ' - ' . Lang::get('encash_bank'));
			$this->import_resource('jquery.plugins/jquery.validate.js');
			$this->display('my_money.encash_bank.html');
		}
	}	
	//提现记录
	function tx_log()
	{
		$user_id = $this->visitor->get('user_id');
		$month = empty($_GET['month']) ? 0 : intval($_GET['month']);
		if ($month == 1){
			$times = strtotime('-1 months');
			$conditions = " and add_time > '$times'";
		}elseif($month == 2){
			$times = strtotime('-3 months');
			$conditions = " and add_time > '$times'";
		}elseif($month == 3){
			$times = strtotime('-6 months');
			
			$conditions = " and add_time > '$times'";
		}elseif($month == 4){
			$times = strtotime('-6 months');
			$conditions = " and add_time < '$times'";
		}else{
			$conditions = " and 1=1";
		}
		$page = $this->_get_page(NUM_PER_PAGE);		
		$my_moneytx_mod = & m('my_moneytx');
		$my_moneytx=$my_moneytx_mod->find(array(
            'conditions' => "user_id='$user_id' " . $conditions,
			'order' => 'add_time desc',
            'limit' => $page['limit'],
			'count' => true,
        ));	
		$ebank_type_check = Lang::get('ebank_type');//银行信息
		foreach ($my_moneytx as $key => $mymoneytx)
		{
			if ($ebank_type_check[$mymoney['bank_name']])
			{
				$my_money[$key]['bank_name_check'] = $ebank_type_check[$mymoney['bank_name']];
			}else{
				$my_money[$key]['bank_name_check'] = $mymoney['bank_name'];
			}	
		}
		$page['item_count'] = $this->my_moneylog_mod->getCount();
        $this->_format_page($page);
	    $this->assign('page_info', $page);
		$this->assign('my_moneytx', $my_moneytx);	
		$this->_curitem('tx_log');
		$this->_curmenu('tx_log');
		$this->_config_seo('title', Lang::get('member_center') . ' - ' . Lang::get('tx_log'));
		$money_money=$this->my_money_mod->getRow("select money,money_dj from ".DB_PREFIX."my_money where user_id='$user_id'");		
		$this->assign('money_money', $money_money);					
		$this->display('my_money.tx_log.html');
		
	}
	function audit_bank()//线下银行充值记录 
	{
	    $user_id = $this->visitor->get('user_id');
		$month = empty($_GET['month']) ? 0 : intval($_GET['month']);
		if ($month == 1){
			$times = strtotime('-1 months');
			$conditions = " and add_time > '$times'";
		}elseif($month == 2){
			$times = strtotime('-3 months');
			$conditions = " and add_time > '$times'";
		}elseif($month == 3){
			$times = strtotime('-6 months');
			
			$conditions = " and add_time > '$times'";
		}elseif($month == 4){
			$times = strtotime('-6 months');
			$conditions = " and add_time < '$times'";
		}else{
			$conditions = " and 1=1";
		}
		$page = $this->_get_page(NUM_PER_PAGE);		
		$my_money=$this->my_moneylog_mod->find(array(
            'conditions' => "user_id='$user_id' and s_and_z=1 and user_log_del=0 and leixing=40" . $conditions,
			'order' => 'add_time desc',
            'limit' => $page['limit'],
			'count' => true,
        ));	
		$ebank_type_check = Lang::get('ebank_type');//银行信息
		foreach ($my_money as $key => $mymoney)
		{
			if ($ebank_type_check[$mymoney['bank_name']])
			{
				$my_money[$key]['bank_name_check'] = $ebank_type_check[$mymoney['bank_name']];
			}else{
				$my_money[$key]['bank_name_check'] = $mymoney['bank_name'];
			}	
		}
		$page['item_count'] = $this->my_moneylog_mod->getCount();
        $this->_format_page($page);
	    $this->assign('page_info', $page);
		$this->assign('my_money', $my_money);	
		$this->assign('money_money', $money_money);
		$this->_curitem('remit_bank');
		$this->_curmenu('audit_bank');
		$this->_config_seo('title', Lang::get('member_center') . ' - ' . Lang::get('audit_bank'));
		$this->display('my_money.audit_bank.html');
	}
		
	//修改支付密码
	function setpaypassword()
	{     	
		$user_id = $this->visitor->get('user_id');
		//读原始密码
		$money_pass=$this->my_money_mod->getOne("select zf_pass from ".DB_PREFIX."my_money where user_id='$user_id'");	
		if($_POST)//检测是否提交
		{
			$y_password = htmldecode($_POST['y_password']);
			$new_password = htmldecode($_POST['new_password']);
			$confirm_password = htmldecode($_POST['confirm_password']);
			//转换32位 MD5
			$md5y_pass=md5($y_password);
			$md5zf_pass=md5($new_password);				
			if(empty($y_password) || empty($new_password))
			{
				$this->show_warning('cuowu_zhifumimabunengweikong'); 
				return;
			}
			if($new_password != $confirm_password)
			{
				$this->show_warning('cuowuliangcishurumimabutong'); 
				return;
			}
			//判断是否已经输入过支付密码了，没有的话就使用登录密码来判断
			if ($money_pass)//没有输入过支付密码的
			{
				if($money_pass != $md5y_pass)
				{
					$this->show_warning('cuowu_zhifumimayanzhengshibai'); 
					return;	
				}				
			}else{
				$member_mod = & m('member');
				$user_name=$member_mod->getOne("select user_name from ".DB_PREFIX."member where user_id='$user_id'");	
				$ms =& ms();
				$user_id = $ms->user->auth($user_name, $y_password);
				if (!$user_id)
				{
					/* 未通过验证，提示错误信息 */
					$this->show_warning($ms->user->get_error());
					return;
				}						
			}

			$newpass_array=array(
			'zf_pass'=>$md5zf_pass,													
			);
			$this->my_money_mod->edit('user_id='.$user_id,$newpass_array);
			$this->show_message('zhifumimaxiugaichenggong');
			return;
		}
		else
		{
            $this->import_resource(array(
                'script' => 'jquery.plugins/jquery.validate.js',
            ));		
			$this->assign('money_pass', $money_pass);	
			$this->_curitem('setpaypassword');
			$this->_curmenu('setpaypassword');
			$this->_config_seo('title', Lang::get('member_center') . ' - ' . Lang::get('setpaypassword'));
			$this->display('my_money.setpaypassword.html');
		}
	}
	//找回支付密码
	function account_security()
	{
		$user_id = $this->visitor->get('user_id');	  
		$money_pass=$this->my_money_mod->getOne("select zf_pass from ".DB_PREFIX."my_money where user_id='$user_id'");
		$member_mod = & m('member');
		$member_email=$member_mod->getOne("select email from {$member_mod->table} where user_id='$user_id'");
		if ($_POST)
		{
			if ($_GET['chooseway'] == 'email_security')
			{
			  if($_POST['goto'] == '1')
			  {
				  if(!$_POST['verifycode'])
				  {
					$this->show_warning('请输入接收到的邮件中的验证码'); 
					return;				  
				  }else{
					//转换32位 MD5
					$md5y_pass=md5($_POST['verifycode']);
					$has_zh_pass=$this->my_money_mod->getOne("select zh_pass from ".DB_PREFIX."my_money where user_id='$user_id'");	
					if ($has_zh_pass != $md5y_pass)
					{
						$this->show_warning('支付验证码错误或者已过期'); 
						return;	
					}
                    $this->import_resource(array('script' => 'jquery.plugins/jquery.validate.js',));							
					$this->assign('md5y_pass', $md5y_pass);
					$this->_curitem('account_security');
					$this->_curmenu('account_security');
					$this->_config_seo('title', Lang::get('member_center') . ' - ' . Lang::get('account_security'));				  
					$this->display('my_money.account_security.html');
				  }
			  }elseif($_POST['goto'] == '2')
			  {
				  $new_password = htmldecode($_POST['new_password']);
				  $confirm_password = htmldecode($_POST['confirm_password']);
				  if(empty($new_password) || empty($confirm_password))
				  {
					  $this->show_warning('支付密码不能为空','返回上一页','index.php?app=my_money&act=account_security&chooseway=email_security'); 
					  return;
				  }				  
				  if($new_password != $confirm_password)
				  {
					  $this->show_warning('cuowuliangcishurumimabutong','返回上一页','index.php?app=my_money&act=account_security&chooseway=email_security'); 
					  return;
				  }
				  //转换32位 MD5
				  $md5zf_pass=md5($new_password);	
				  //$word = $this->_rand();
                  //$md5word = md5($word);			  
				  $this->my_money_mod->edit('user_id='.$user_id,array('zf_pass'=>$md5zf_pass,'zh_pass'=>'',));
				  header('Location: index.php?app=my_money&act=account_security&chooseway=ok');
			  }
		  	}
 
		}else{
			if (empty($money_pass))
			{
				//header('Location: index.php?app=my_money&act=setpaypassword');
				$this->show_warning('cuowu_zhifumimameiyousezhi',
				'back_sezhimima', 'index.php?app=my_money&act=setpaypassword'); 
				return;	
			}
			$this->assign('money_pass', $money_pass);
			$this->assign('member_email', $member_email);
			$this->_curitem('setpaypassword');
			$this->_curmenu('setpaypassword');
			$this->_config_seo('title', Lang::get('member_center') . ' - ' . Lang::get('account_security'));		
			$this->display('my_money.account_security.html');
		}
	}

    /**
     *    生成订单号
     */
    function _gen_order_sn()
    {
        /* 选择一个随机的方案 */
        mt_srand((double) microtime() * 1000000);
        $timestamp = gmtime();
        $y = date('y', $timestamp);
        $z = date('z', $timestamp);
        $order_sn = $y . str_pad($z, 3, '0', STR_PAD_LEFT) . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);

        $model_order =& m('my_moneylog');
        $orders = $model_order->find('pay_order_sn=' . $order_sn);
        if (empty($orders))
        {
            /* 否则就使用这个订单号 */
            return $order_sn;
        }

        /* 如果有重复的，则重新生成 */
        return $this->_gen_order_sn();
    }	
    /**
     * 构造15位的随机字符串
     *
     * @return string | 生成的字符串
     */
    function _rand()
    {
        $word = $this->generate_code();
        return $word;
    }

    function generate_code($len = 15)
    {
        $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        for ($i = 0, $count = strlen($chars); $i < $count; $i++)
        {
            $arr[$i] = $chars[$i];
        }

        mt_srand((double) microtime() * 1000000);
        shuffle($arr);
        $code = substr(implode('', $arr), 5, $len);
        return $code;
    }
	function SendEmail()
	{
		//定义user_id=登陆ID
        $user_id = $this->visitor->get('user_id');
		$user_email = $_GET['email'];
		if (!$user_email)
		{
			echo('false');
			return;
		}
		if (!is_email($user_email))
		{
			echo('false');
			return;
		}		
		$word = $this->_rand();
		$md5word = md5($word);
		$this->my_money_mod->edit("user_id = ".$user_id, array('zh_pass' => "{$md5word}"));
		$mail = get_mail('touser_find_zfpassword', array('user_name' => $this->visitor->get('user_name'), 'word' => $word));
		$this->_mailto($user_email, addslashes($mail['subject']), addslashes($mail['message']));	
		echo('ture');
		return;
	}
	
    /**
     *    三级菜单
     *
     *    @author liangcajian QQ632324010
     *    @return    void
     */
    function _get_member_submenu()
    {
        $menus = array(
            array(
                'name'  => 'remit_alipay',
                'url'   => 'index.php?app=my_money&act=remit_alipay',
            ),
            array(
                'name'  => 'audit_ailpay',
                'url'   => 'index.php?app=my_money&act=audit_ailpay',
            ),			
            array(
                'name'  => 'my_money_index',
                'url'   => 'index.php?app=my_money',
            ),	
            array(
                'name'  => 'setpaypassword',
                'url'   => 'index.php?app=my_money&act=setpaypassword',
            ),					
        );			

        return $menus;
    }	 

}
?>
